import 'package:chathouse/constant/app_constant.dart';
import 'package:chathouse/pages/login/login_page.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';
import 'dart:math';
import 'dart:io';

import '../../model/response_bean.dart';
import '../../util/log.dart';
import '../client/client_root_container.dart';

///选择用户类型
class SelectRolePage extends StatefulWidget {
  const SelectRolePage({Key? key}) : super(key: key);

  setController() {}

  @override
  State<SelectRolePage> createState() => _SelectRolePageState();
}

class _SelectRolePageState extends State<SelectRolePage>
    with TickerProviderStateMixin {
  bool showSelectRoleWidget = false;
  double opacity = 0.0;
  double gifOpacity = 1.0;
  late VideoPlayerController videoController;
  var showVideo = false;
  var isShowTour = false; //是否顯示遊客模式

  @override
  void initState() {
    super.initState();
    videoController = VideoPlayerController.asset(
      'assets/anim.mp4',
    );
    videoController.initialize().then((_) {
      showVideo = true;
      videoController.setLooping(false);
      videoController.play();
      videoController.addListener(() {
        // LogUtil.d("播放: ${videoController.value}");
        if (videoController.value.position >= videoController.value.duration) {
          //播放完成
          setState(() {
            showSelectRoleWidget = true;
          });
        }
      });
      setState(() {});
    });
    Apis.isShowTourist().then((value) async {
      var result = ResponseBean.fromJson(value?.data ?? {});
      if (result.isRequestSuccess) {
        setState(() {
          isShowTour = true;
        });
      }
    }).catchError((error) {
      LogUtil.d("isShowTourist Error $error");
    });
  }

  login() {
    ResponseBean result;
    var random = Random();
    var randomNumber = random.nextInt(1000000);
    Apis.touristregister({"registrationId": randomNumber.toString()})
        .then((value) {
      result = ResponseBean.fromJson(value?.data ?? {});
      if (result.isRequestSuccess) {
        SpUtil.putString(Keys.token, value?.data[Keys.token]);
        SpUtil.putString(Keys.userRole, "c");
        AppConstant.token = value?.data[Keys.token];
        Get.offAll(const ClientRootPage());
      }
    }).onError((error, stackTrace) {});
  }

  DateTime? startTime;

  @override
  void dispose() {
    videoController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Stack(
        children: [
          Stack(
            children: [
              Container(
                  child:
                      showVideo ? VideoPlayer(videoController) : Container()),
              Visibility(
                visible: showSelectRoleWidget,
                child: Stack(
                  children: [
                    // ImageUtils.image(Res.login_bg, width: 1.sw, height: 1.sh),
                    ListView(
                      children: [
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            /* ImageUtils.image(Res.login_logo,
                                  width: 145.w, height: 160.w)
                              .setContainer(margin: EdgeInsets.only(top: 80.w)),*/
                            Text(
                              "用戶登入或註冊",
                              style: getTextStyle(32.sp,
                                  fontType: FontType.BOLD, color: Colors.white),
                            )
                                .setContainer(
                                    margin: EdgeInsets.only(top: 60.w),
                                    padding: EdgeInsets.symmetric(
                                        horizontal: 26.w, vertical: 36.w),
                                    decoration: BoxDecoration(
                                        color: MyColors.brown_25118177,
                                        borderRadius:
                                            BorderRadius.circular(26.w)))
                                .setOnClickListener(() {
                              selectUser(UserRole.c);
                            }),
                            Text(
                              "服務專家登入或註冊",
                              style: getTextStyle(22.sp,
                                  fontType: FontType.BOLD, color: Colors.white),
                            )
                                .setContainer(
                                    margin: EdgeInsets.only(top: 27.w),
                                    padding: EdgeInsets.symmetric(
                                        horizontal: 36.w, vertical: 11.w),
                                    decoration: BoxDecoration(
                                        color: MyColors.green_69157154,
                                        borderRadius:
                                            BorderRadius.circular(26.w)))
                                .setOnClickListener(() {
                              selectUser(UserRole.b);
                            }),
                            Visibility(
                              visible: Platform.isIOS && isShowTour,
                              child: const Text(
                                "暫不註冊,進入首頁",
                                style: TextStyle(
                                    fontWeight: FontWeight.w600,
                                    fontSize: 16,
                                    color: Colors.white),
                              )
                                  .setContainer(
                                      margin: EdgeInsets.only(top: 27.w),
                                      padding: EdgeInsets.symmetric(
                                          horizontal: 36.w, vertical: 11.w),
                                      decoration: BoxDecoration(
                                          color: Styles.mainColor,
                                          borderRadius:
                                              BorderRadius.circular(26.w)))
                                  .setOnClickListener(() {
                                login();
                              }),
                            ),
                          ],
                        )
                      ],
                    ).setContainer(margin: EdgeInsets.only(top: 260.w))
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  void selectUser(UserRole role) {
    debugPrint("selectUser=${role.toString()}");
    SpUtil.putString(Keys.userRole, role == UserRole.c ? "c" : "b");
    AppConstant.userRole = role;
    Get.to(LoginPage());
  }
}
